// axios工具函数管理层

import store from "@/store";
import axios from "axios";
import { Message } from "element-ui";

// 封装公共地址和超时时间
const instance = axios.create({
	baseURL: "http://sell.h5.itsource.cn:8087",
	timeout: 30000,
});

// 封装请求拦截器
instance.interceptors.request.use(
	(config) => {
		let token = store.getters.token;
		config.headers.Authorization = token;
		return config;
	},
	(err) => {
		return Promise.reject(err);
	}
);

// 封装响应拦截器
instance.interceptors.response.use(
	(response) => {
		// 处理成功状态码
		let { code, msg } = response.data;
		if (code == 0) {
			Message.success(msg);
		}
		if (code == 1) {
			Message.error(msg);
		}
		if (code == 5001) {
			Message.error(msg);
		}
		return response;
	},
	(err) => {
		// 处理失败状态码
		let { message, response } = err;
		if (response) {
			switch (response.status) {
				case 401:
					Message.error(message);
					break;
				case 403:
					Message.error(message);
					break;
				case 404:
					Message.error(message);
					break;
				case 500:
					Message.error(message);
					break;

				default:
					break;
			}
		}else{
			Message.error(message);
		}
		return Promise.reject(err);
	}
);

// 导出
export default instance;
